import dayjs from "dayjs";

/** 购物车 */
const shoppingCard = {
  namespaced: true,
  state: {
    // 购物车当前数据列表
    cardlist: [],
    isPack: 0, // 是否打包
    useMember: false, // 是否登录会员
    member: {}, // 会员信息 useMember = true 时使用,
    // 存单信息
    depositReceipt: uni.getStorageSync("__APP__depositReceipt") || {
      isPack: 0, // 是否打包
      useMember: false, // 是否登录会员
      member: {}, // 会员信息 useMember = true 时使用,
      productList: [], // 商品列表
      saveTime: "", // 存单时间 (如果非同一天，则清除存单)
    },
  },
  actions: {},
  mutations: {
    /** 设置购物车商品信息 */
    setCurrShoppingCard(state: any, data: any) {
      state.useMember = !!(data.useMember);
      state.member = data.member ? data.member : {};
      state.isPack = data.isPack ? data.isPack : 0;
      if (data.productList) {
        state.cardlist = data.productList;
        // 通知更新
        uni.$emit("cart-item:update", state.cardlist);
      }
    },
    /** 设置购物车商品信息 */
    setCardlist(state: any, data: any) {
      state.cardlist = data;
      // 通知更新
      uni.$emit("cart-item:update", state.cardlist);
    },
    /** 设置存单信息 */
    setDepositReceipt(state: any, data: any) {
      state.depositReceipt = data;
      const fullData = {
        isPack: 0, // 是否打包
        useMember: false, // 是否登录会员
        member: {}, // 会员信息 useMember = true 时使用,
        productList: [], // 商品列表
        saveTime: dayjs().format("YYYY/MM/DD HH:mm:ss"), // 存单时间 (如果非同一天，则清除存单)
      };
      if (data.useMember) fullData.useMember = data.useMember;
      if (data.member) fullData.member = data.member;
      if (data.isPack) fullData.isPack = data.isPack;
      if (data.productList) fullData.productList = data.productList;
      state.depositReceipt = fullData;
      uni.setStorageSync("__APP__depositReceipt", fullData);
    },
    onLogout(state) {
      // 退出登陆时，会调用该方法，需要再此处理相关业务数据的，在这写；默认会清除所有业务数据
      state.useMember = false;
      state.member = {};
      state.isPack = 0;
      state.cardlist = [];
    },
    clear(state: any) {
      // 清除数据
      const clearKeys = Object.keys(state);
      clearKeys.forEach((key) => {
        const keyName = "__APP__" + key;
        state[keyName] = {};
        uni.removeStorageSync(keyName);
      });
    },
  },
  getters: {
    currShoppingCardInfo: (state: any) => {
      return {
        useMember: state.shoppingCard.useMember,
        member: state.shoppingCard.member,
        isPack: state.shoppingCard.isPack,
        productList: state.shoppingCard.cardlist,
      };
    },
    shoppingCart: (state: any) => state.shoppingCard.cardlist,
    depositReceipt: (state: any) => state.shoppingCard.depositReceipt,
  },
};
export default shoppingCard;
